package com.cbc.ourgame.slideshowmaker.components.ui
{
	import caurina.transitions.Equations;
	import caurina.transitions.Tweener;
	
	import flash.display.Sprite;
	
	public class Clock extends Sprite
	{
		private const RADIAN:Number = Math.PI/180;
		private var _radius:Number;
		private var _angle:Number;
		
		private var _circleMask:Sprite;
		private var _clock:Sprite;
		private var _background:Sprite;
		
		private var _baseColor:uint;
		private var _backgroundColor:uint;
		
		public function get angle():Number
		{
			return _angle;
		}
		
		public function set angle(value:Number):void
		{
			_angle = value;
			updateClock();
		}
		
		public function Clock(radius:Number, baseColor:uint, outlineColor:uint)
		{
			_radius = radius;
			_baseColor = baseColor;
			_backgroundColor = outlineColor;
			
			_angle = 0;
			
			createBackground();
			_clock = new Sprite();
			_clock.rotation = -90;
			addChild(_clock);
			createMask();
		}
		
		public function start(time:Number):void
		{
			visible = true;
			Tweener.addTween(this, {angle:360, time:time, transition:Equations.easeNone});
			_angle = 0;
		}
		
		public function resume():void
		{
			Tweener.resumeTweens(this);	
		}
		
		public function pause():void
		{
			Tweener.pauseTweens(this);
		}
		
		public function stop():void
		{
			Tweener.removeTweens(this);
			_angle = 0;
			updateClock();
			visible = false;
		}
		
		private function createMask():void
		{
			_circleMask = new Sprite();
			_circleMask.graphics.beginFill(0xFFFFFF,0.5);
			_circleMask.graphics.drawCircle(0,0,_radius-5);
			_circleMask.graphics.endFill();
			addChild(_circleMask);
			
			_clock.mask = _circleMask;
		}
		
		private function updateClock():void
		{

			_clock.graphics.clear();
			
			_clock.graphics.lineStyle(0,0,0);
			_clock.graphics.beginFill(_baseColor, 1);
			_clock.graphics.moveTo(0,0);
			_clock.graphics.lineTo(_radius, 0);
			
			var angChunk:Number = _angle/6;
			
			for(var i:int = 0; i<6; i++)
			{
				var calcAng:Number = angChunk*(i+1);
				var xPos:Number = _radius * Math.cos(calcAng*RADIAN);
				var yPos:Number = _radius * Math.sin(calcAng*RADIAN);
				
				_clock.graphics.lineTo(xPos, yPos);
			}
			
			_clock.graphics.lineTo(0,0);
			_clock.graphics.endFill();
		}
		
		private function createBackground():void
		{
			_background = new Sprite();
			_background.graphics.lineStyle(1,_backgroundColor,1,true);
			_background.graphics.beginFill(_backgroundColor,1);
			_background.graphics.drawCircle(0,0,_radius-1);
			_background.graphics.endFill();
			addChild(_background);
		}

	}
}